package com.github.defense.plugin.gray.configuration;

import com.github.defense.plugin.gray.context.GrayLocalContext;
import com.github.defense.plugin.gray.context.RoutingHandler;
import com.github.defense.plugin.gray.netflix.hystrix.HystrixLocalContext;
import com.github.defense.plugin.gray.netflix.rest.GrayClientHttpRequestInterceptor;
import com.github.defense.plugin.gray.netflix.rest.RestGrayInterceptor;
import com.netflix.loadbalancer.ILoadBalancer;
import feign.Feign;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration;
import org.springframework.cloud.netflix.ribbon.RibbonClients;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

/**
 * @Author: lettger
 * @Date: 2021/6/19 7:17 上午
 */
@Configuration
@AutoConfigureBefore(RibbonClientConfiguration.class)
@RibbonClients(defaultConfiguration = GrayRibbonConfiguration.class)
@ConditionalOnClass(value = {ILoadBalancer.class, Feign.class})
@EnableFeignClients(defaultConfiguration = {GrayFeignClientsConfiguration.class})
public class GrayNetflixAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean(GrayLocalContext.class)
    public GrayLocalContext hystrixLocalContext(){
        return new HystrixLocalContext();
    }

    @LoadBalanced
    @Bean
    public RestTemplate restTemplate(RoutingHandler handler){
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getInterceptors().add(new GrayClientHttpRequestInterceptor(handler));
        return restTemplate;
    }


    @Bean
    public RestGrayInterceptor restGrayInterceptor(){
        return new RestGrayInterceptor();
    }

}
